//
//  DisplayBabyGrowView.m
//  BabyHelper
//
//  Created by  thomas on 11-6-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DisplayBabyGrowView.h"


@implementation DisplayBabyGrowView
@synthesize babyGrowEntries;
@synthesize photoManager;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
	self.photoManager = [PhotoManager getInstance];
	self.babyGrowEntries = [[NSMutableArray alloc]init];
	self.title = NSLocalizedString(@"Grows",@"");
    [super viewDidLoad];
	
	UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc]
								   initWithTitle:NSLocalizedString(@"Del",@"")
								   style:UIBarButtonItemStyleBordered 
								   target:self
								   action:@selector(toggleDelete)		
								   ];
	self.navigationItem.leftBarButtonItem = deleteItem;
	[deleteItem release];
	
	UIBarButtonItem *addItem = [[UIBarButtonItem alloc]
								initWithTitle:NSLocalizedString(@"Add",@"")
								style:UIBarButtonItemStyleBordered 
								target:self
								action:@selector(toggleAdd)		
								];
	self.navigationItem.rightBarButtonItem = addItem;
	[addItem release];
	
	//set background image
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
	self.view.backgroundColor = [UIColor clearColor];
	//set navigation background color
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha];
	
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	Dao *dao = [Dao getInstance];
	
	[self.babyGrowEntries removeAllObjects];
	NSString *whereClause = @"WHERE BabyGrowTable.PhotoID = PhotoTable.ID ORDER BY BabyGrowTable.TIMESTAMP DESC";
	[dao QueryBabyGrowEntryWith:whereClause records:self.babyGrowEntries];
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.babyGrowEntries count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"BabyGrowTableViewCellIdentifier";
    
    BabyGrowTableViewCell *cell = (BabyGrowTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BabyGrowTableViewCell"  owner:self options:nil];
		for( id oneObject in nib)
			if( [oneObject isKindOfClass:[BabyGrowTableViewCell class]])
				cell = (BabyGrowTableViewCell *)oneObject;
    }
    
    // Configure the cell...
	BabyGrowEntry *entry = [self.babyGrowEntries objectAtIndex:indexPath.row];	
	cell.timestampLabel.text = [entry getDateString];
	Dao *dao = [Dao getInstance];
	BabyProfile *babyProfile = [[BabyProfile alloc]init];
	[dao LoadBabyProfile:babyProfile];
	cell.ageLabel.text = [dao GetAgeStringWithTwoDate:babyProfile.Birthday toDateTS:[entry.timestamp timeIntervalSince1970]];
	[babyProfile release];
	cell.heightValueLabel.text  = [NSString stringWithFormat:@"%@:%.1fcm",NSLocalizedString(@"H",@""),entry.height];
	cell.weightValueLabel.text  = [NSString stringWithFormat:@"%@:%.1fkg",NSLocalizedString(@"W",@""),entry.weight];
	cell.headCirValueLabel.text = [NSString stringWithFormat:@"%@:%.1fcm",NSLocalizedString(@"HC",@""),entry.headCir];
	//cell.heightLabel.text       = NSLocalizedString(@"Height",@"");
	//cell.weightLabel.text       = NSLocalizedString(@"Weight",@"");
	//cell.headCirLabel.text      = NSLocalizedString(@"HeadCir",@"");
	
	NSLog(@"File Path is %@",entry.photoPath);
	
	//[cell setBackgroundColor:[UIColor clearColor]];
	[cell setBackgroundColor:[UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha]];
	
	NSLog(@"%@",entry.thumPath);
	if ([entry.thumPath isEqualToString:@"null"])
		cell.imageView.image = [UIImage imageNamed:@"babygrowicon"];
	else 
	{
		cell.imageView.image = [photoManager GetThumPhotoByBabyGrowID:entry.photoID];
		//cell.imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.thumPath]];
	}
 
	UIImage *image   = [UIImage imageNamed:@"Sina_32x32"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
	button.frame = frame;	// match the button's size with the image size
	[button setBackgroundImage:image forState:UIControlStateNormal];
	// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
	[button addTarget:self action:@selector(accessoryButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
	cell.backgroundColor = [UIColor colorWithRed:cellBackgroundRed green:cellBackgroundGreen 
											blue:cellBackgroundBlue alpha:cellBackgroundAlpha];

	cell.accessoryView = button;

    return cell;
}

- (void)accessoryButtonTapped:(id)sender event:(id)event
{
	NSSet *touches = [event allTouches];
	UITouch *touch = [touches anyObject];
	CGPoint currentTouchPosition = [touch locationInView:self.tableView];
	NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
	if (indexPath != nil)
	{
		[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
	}
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{	
	BabyHelperAppDelegate *appDelegate = (BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: appDelegate._engine delegate: self];
	if (controller) 
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
														message:NSLocalizedString(@"You are not log in yet", @"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	else {
		NSLog(@"Authenicated for %@..", appDelegate._engine.username);
		[OAuthEngine setCurrentOAuthEngine:appDelegate._engine];
		[[NSUserDefaults standardUserDefaults] setValue:[self GetReportContentWithIndexPath:indexPath] forKey:@"SavedWeiBoText"];
		ComposeViewController *composeViewController = [[ComposeViewController alloc]init];
		[self presentModalViewController:composeViewController animated:YES];
		composeViewController.messageTextField.text = [self GetReportContentWithIndexPath:indexPath];
		
		[composeViewController newTweet];					
		
		BabyGrowEntry *entry = [self.babyGrowEntries objectAtIndex:indexPath.row];
		
		if ( ![entry.photoPath isEqualToString:@"null"] ) {
			UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.photoPath]];
			[composeViewController setImage:image movie:nil];
		}
	}	
}

-(NSString *)GetReportContentWithIndexPath:(NSIndexPath *)indexPath{
	
	BabyGrowEntry *entry = [self.babyGrowEntries objectAtIndex:indexPath.row];	
	Dao *dao = [Dao getInstance];
	BabyProfile *babyProfile = [[BabyProfile alloc]init];
	[dao LoadBabyProfile:babyProfile];

	NSString *report = [NSString stringWithFormat:BABY_GROW_ENTRY_CONTENT_STR,
						babyProfile.Name,
						[dao GetAgeStringWithTwoDate:babyProfile.Birthday toDateTS:[entry.timestamp timeIntervalSince1970]],
						entry.height,
						entry.weight,
						entry.headCir];
	[babyProfile release];
	
	return report;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		BabyGrowEntry *entry = [self.babyGrowEntries objectAtIndex:[indexPath row]];
		
		//if change the pic, should delete old pic first;
		if(![entry.photoPath isEqualToString:@"null"] &&
		   ![entry.thumPath isEqualToString:@"null"])
		{
			remove([[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.photoPath] cStringUsingEncoding:NSASCIIStringEncoding]);
			remove([[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),entry.thumPath] cStringUsingEncoding:NSASCIIStringEncoding]);
		}
		[photoManager RemoveThumImageByBabyGrowID:entry.photoID];
		
		Dao *dao = [Dao getInstance];
		[dao RemoveBabyGrowEntry:entry];
		[self.babyGrowEntries removeObjectAtIndex:[indexPath row]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	EditBabyGrowEntryView *childView = [[EditBabyGrowEntryView alloc] initWithNibName:@"EditBabyGrowEntryView" bundle:nil];
	childView.currentBabyGrowEntry = [self.babyGrowEntries objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:childView animated:YES];
	[childView release];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[self.babyGrowEntries release];
}

-(void)toggleAdd{
	EditBabyGrowEntryView *childView = [[EditBabyGrowEntryView alloc] initWithNibName:@"EditBabyGrowEntryView" bundle:nil];
	childView.currentBabyGrowEntry = nil;
	[self.navigationController pushViewController:childView animated:YES];
	[childView release];
}

-(void)toggleDelete{
	[self.tableView setEditing:!self.tableView.editing animated:YES];
	
	if (self.tableView.editing)
		[self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"Done",@"")];
	else
		[self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"Del",@"")];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return kBabyGrowTableViewRowHeight;
}
@end